import re
import json
from frame_work.setting import *
from frame_work.yaml_file import YAML
from frame_work.util import check_tid, assert_result_dict, change_user_account_status, get_sql_info
from frame_work.logger import Logger
from frame_work.login import PcLogin
from frame_work import menu_list
from requests_toolbelt import MultipartEncoder
from frame_work.setting import image_Path

logger = Logger(__name__).get_logger()


class SubmitReport(object):

    def __init__(self, tid, uname):
        self.tid = tid
        self.uname = uname
        self.yaml = YAML(os.path.join(base_Dir, 'data', 'data.yaml'))
        self.session = self.get_session()

    def get_session(self):
        """
        :return:返回登录用户session
        """
        login = PcLogin(self.uname)
        login.pc_login()
        return login.get_session()

    def echo_report_pic_addr(self, rid, title):
        """
        发布活动中会含有上传图片的操作，此函数在作用post一张图片到图片服务器，获取响应值类似：tmp/2019/08/20/08500820924072552490.jpg
        :param num:第几张图片
        :param title:活动类型与来源的拼接
        :return:pic_addr
        """
        shikee_cookies = self.session.cookies.get(
            'shikee')  # 获取用户cookies中的shikee部分
        yaml_data = self.yaml.get_data('report_pic')
        yaml_data.get('data').update({
            'name': title,
            'Filedata': ('filename', open(os.path.join(image_Path, title), 'rb'), 'image/jpg')
        })
        url = yaml_data.get('url') + '?rid=' + str(rid) + \
            '&type=1&swf_upload_cookie=' + shikee_cookies
        m = MultipartEncoder(
            fields=yaml_data.get('data')
        )
        r = self.session.post(url, data=m,
                              headers={'Content-Type': m.content_type})
        return json.loads(r.text).get("data")[0].get('url')

    def get_report_id(self, jid):
        """
        获取初始rid
        :param jid:
        :return:
        """
        rid = ''
        yaml_data = self.yaml.get_data('report_id')
        res = self.session.get(yaml_data.get('url') + '/' + str(jid))
        if res.status_code == 200:
            rid = re.findall(r'id="J_Rid" value="(.*?)"', res.text)[0]
        return rid

    def submit_report(self):
        """
        提交报告
        :return:
        """
        status = change_user_account_status(self.uname)
        if not status:
            logger.debug("用户账号状态不对,无法提交报告")
            return
        logger.debug("提交报告前，进行用户登录操作...")
        statement = """SELECT jid from sk_join WHERE buyer_uname = %s and tid = %s"""
        params = (self.uname, self.tid)
        value = get_sql_info(statement, params, meta={
            "info": "获取参与jid"
        })
        rid = self.get_report_id(value[0].get("jid"))
        whole_imgs = []
        details_imgs = []
        self_show = []
        whole_img1 = self.echo_report_pic_addr(rid, '精细报告_整体图片1.jpg')
        whole_img2 = self.echo_report_pic_addr(rid, '精细报告_整体图片2.jpg')
        whole_img3 = self.echo_report_pic_addr(rid, '精细报告_整体图片3.jpg')
        whole_imgs.append(whole_img1)
        whole_imgs.append(whole_img2)
        whole_imgs.append(whole_img3)
        details_img1 = self.echo_report_pic_addr(rid, '精细报告_细节图片1.jpg')
        details_img2 = self.echo_report_pic_addr(rid, '精细报告_细节图片2.jpg')
        details_imgs.append(details_img1)
        details_imgs.append(details_img2)
        self_show_img = self.echo_report_pic_addr(rid, '精细报告_真人秀.jpg')
        self_show.append(self_show_img)
        yaml_data = self.yaml.get_data('submit_report')
        yaml_data.get('data').update({
            'rid': rid,
            'img_selfie[]': self_show,
            'img_process[]': whole_imgs,
            'img_detail[]': details_imgs
        })
        # 提交报告
        logger.debug("开始提交报告...")
        response = self.session.post(
            url=yaml_data.get('url'),
            data=yaml_data.get('data'),
            headers=yaml_data.get('header')).text
        assert_result_dict(response, self.uname + '提交精细报告rid:' + rid)


def main():
    while True:
        # 显示功能菜单
        menu_list.quality_submit_report_menu()
        choise = input("请输入您的选择: ")
        if choise in ('q', 'Q'):
            break
        try:
            tid = int(input(u'请输入活动tid: '))
            status = check_tid(tid)
            if not status:
                raise Exception("活动tid不存在try表，请核实后在重新输入")
        except Exception as e:
            logger.error("reszon => %s" % e)
        else:
            if choise == '1':
                buyer_name = input(u"请输入要提交报告的试客名称: ")
                report = SubmitReport(tid, buyer_name)
                report.submit_report()
            else:
                logger.info("没有对应的选项,请按选项输入...")
                break


if __name__ == "__main__":
    main()
